package com.dragon.www.haier.net;

import android.util.Log;

import java.io.IOException;
import java.io.Serializable;
import java.net.DatagramPacket;
import java.net.SocketAddress;
import java.nio.ByteBuffer;

/**
 * * 指令格式：
 * ****************************** *
 * **   HEADER 2 bytes         ** *
 * **   TYPE  1 bytes          ** *
 * **   LENGTH 4 bytes         ** *
 * **   DATA   ? bytes         ** *
 * **   CS     1 bytes         ** *
 * **   END    2 bytes         ** *
 * ****************************** *
 */

/**
 * Created by Administrator on 2015/10/28 16:08.
 * Author: songxy
 * Email: thinkdata@163.com
 */
public abstract class AUDPPacket implements Serializable {

    /**
     * 组网内部报文
     */
    protected DatagramPacket mPacket;

    protected SocketAddress mSocketAddress;

    public abstract boolean hasData();
    /**
     * @return
     */
    public DatagramPacket getPacket() {
        return mPacket;
    }

    /**
     * 新建mPacket用于Udp接收包
     *
     * @return
     */
    public DatagramPacket newPacket() {
        byte[] data = new byte[totalLength()];
        this.mPacket = new DatagramPacket(data, data.length);
        return this.mPacket;
    }

    public DatagramPacket newPacket(int mPacketLength) {
        byte[] data = new byte[mPacketLength];
        this.mPacket = new DatagramPacket(data, data.length);
        return this.mPacket;
    }

    public SocketAddress getSocketAddress() {
        return mSocketAddress;
    }

    public void setSocketAddress(SocketAddress socketAddress) {
        mSocketAddress = socketAddress;
    }

    public abstract byte[] getAction();

    /**
     * 总长度
     *
     * @return
     */
    protected abstract int totalLength();

    /**
     * 校验值
     *
     * @return
     */
    protected abstract void checksum();

    /**
     * 序列化输出对象
     *
     * @return
     */
    protected abstract void writePacketObject(DatagramPacket packet) throws IOException;

    /**
     * 序列化输入对象
     *
     * @throws IOException
     * @throws ClassNotFoundException
     */
    protected abstract ByteBuffer readPacketHeader(DatagramPacket packet) throws IOException, ClassNotFoundException;

    protected abstract void readPacketObject(ByteBuffer bb) throws IOException, ClassNotFoundException;

    protected abstract void readPacketTail(ByteBuffer bb) throws IOException, ClassNotFoundException;

    public Object clone() {
        Object obj = null;
        try {
            obj = (AUDPPacket) super.clone();
        }catch (CloneNotSupportedException e) {
            Log.e("AppDatagramPacket", e.getMessage());
        }
        return  obj;
    }
}
